<template>
  <div id="container">
    <div class="password-form">
      <p class="title">忘记密码</p>
      <el-form label-width="100px" :model="form" :rules="rules" ref="formRef">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名"></el-input>
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入注册手机号"></el-input>
        </el-form-item>

        <el-form-item label="验证码" prop="code">
          <el-input v-model="form.code" placeholder="请输入验证码" style="width: 60%; display: inline-block; margin-right: 10px;"></el-input>
          <el-button :disabled="isSending" @click="getCode" style="width: 30%; display: inline-block;">
            {{ isSending ? countdown + 's' : '获取验证码' }}
          </el-button>
        </el-form-item>

        <el-form-item label="新密码" prop="newPassword">
          <el-input type="password" v-model="form.newPassword" placeholder="请输入新密码"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm">确 认</el-button>
          <el-button @click="cancel">取 消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { forgetPasswordApi, sendCodeApi } from '../../api/login';

  import { useLoginEmpStore } from '../../stores/loginEmp';


const formRef = ref(null)
const form = ref({
  username: '',
  phone: '',
  code: '',
  newPassword: ''
})

const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  code: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6位', trigger: 'blur' }
  ]
}

const router = useRouter()
const isSending = ref(false)
const countdown = ref(60)
let timer = null

// 获取验证码
const getCode = async () => {
  if (isSending.value) return
  if (!form.value.phone) {
    ElMessage.error('请先输入手机号')
    return
  }
  
  try {
    isSending.value = true
    const result = await sendCodeApi({ phone: form.value.phone })
    if (result.code === 200) {
      ElMessage.success('验证码发送成功')
      startCountdown()
    } else {
      ElMessage.error(result.msg || '验证码发送失败')
      isSending.value = false
    }
  } catch (error) {
    console.error('发送验证码失败', error)
    ElMessage.error('操作失败，请稍后再试')
    isSending.value = false
  }
}

// 倒计时
const startCountdown = () => {
  countdown.value = 60
  timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer)
      isSending.value = false
    }
  }, 1000)
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const result = await forgetPasswordApi(form.value)
        if (result.code === 200) {
          ElMessage.success('密码重置成功')
          router.push('/login?username=' + form.value.username)
        } else {
          ElMessage.error(result.msg || '密码重置失败')
        }
      } catch (error) {
        console.error('重置密码失败', error)
        ElMessage.error('操作失败，请稍后再试')
      }
    } else {
      console.log('验证失败')
      return false
    }
  })
}

const cancel = () => {
  router.push('/login')
}

// 组件卸载时清除定时器
onMounted(() => {
  return () => {
    if (timer) {
      clearInterval(timer)
    }
  }
})
</script>

<style scoped>
/* 样式与UpdatePassword.vue相同，可复制使用 */
#container {
  padding: 10%;
  height: 100vh;
  background-image: url('../../public/loginBG.png');
  background-repeat: no-repeat;
  background-size: cover;
  display: flex;
  justify-content: center;
  align-items: center;
}

.password-form {
  max-width: 500px;
  padding: 40px;
  margin: 0 auto;
  border-radius: 12px;
  backdrop-filter: blur(8px);
  background-color: rgba(255, 255, 255, 0.5);
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
  border: 2px solid rgba(255, 16, 16, 0.4);
}

.title {
  font-size: 32px;
  font-family: '楷体';
  text-align: center;
  margin-bottom: 35px;
  font-weight: bold;
  color: #333;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-input {
  width: 100%;
}

/* 响应式调整 */
@media (max-width: 600px) {
  .password-form {
    padding: 30px 20px;
    max-width: 90%;
  }
  
  .title {
    font-size: 28px;
  }
}
</style>